package com.yzpass.api.user.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yzpass.api.common.Result;
import com.yzpass.api.common.config.YzConfig;
import com.yzpass.api.common.util.JwtUtil;
import com.yzpass.api.common.util.SHAUtil;
import com.yzpass.api.user.dto.AuthInfoDTO;
import com.yzpass.api.user.dto.LoginDTO;
import com.yzpass.api.user.entity.User;
import com.yzpass.api.user.mapper.UserMapper;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.NotBlank;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 用户登录相关逻辑
 */
@Service
public class LoginService {

    @Resource
    UserMapper userMapper;

    @Resource
    YzConfig yzConfig;

    SHAUtil shaUtil = new SHAUtil();
    public Result<AuthInfoDTO> login(LoginDTO loginDTO) {
        String message = "用户名或密码错误";
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,loginDTO.getUsername());
        User user = userMapper.selectOne(queryWrapper);

        if(user==null){
            return Result.warn(message);
        }

        if(!passOk(user,loginDTO.getPassword())){
            return  Result.warn(message);
        }
        return Result.success(genAuth(user));
    }

    private AuthInfoDTO genAuth(User user) {
        AuthInfoDTO dto = new AuthInfoDTO();
        dto.setUsername(user.getUsername());
        dto.setUserId(user.getUserId().toString());
        dto.setName(user.getName());
        Date exp = new Date();
        // 过期时间
        exp.setTime(System.currentTimeMillis() + 8 * 60 * 60 * 1000L);
        dto.setAccessToken(JwtUtil.generate(exp,yzConfig.getPrivateKey(),user));
        return dto;
    }

    /**
     * 密码算法 sha256(sha256(原始密码) + 盐), 前端传过来的是 sha256(原始密码)
     * @param user
     * @param password
     * @return
     */
    private boolean passOk(User user, @NotBlank String password) {
        String target = encryptStep2(password , user.getSalt());
        return target.equals(user.getPassword());
    }

    public String encrypt(String plainPassword, String salt){
        String p1 = encryptStep1(plainPassword);
        return encryptStep2(p1,salt);
    }

    public String encryptStep1(String plainPassword){
        return  shaUtil.SHA256(plainPassword);
    }

    public String encryptStep2(String password, String salt){
        return  shaUtil.SHA256(password + salt);
    }
}
